package com.example.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.backend.util.AuthUtil;
import com.example.backend.entity.Account;
import com.example.backend.mapper.AccountMapper;
import com.example.backend.service.AdminService;
import com.example.backend.util.WeBASEUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private WeBASEUtils weBASEUtils;
    
    @Autowired
    private AuthUtil authUtil;
    
    @Autowired
    protected AccountMapper accountMapper;

    @Override
    public String login(String accountId, String password, Integer accountType) {
        return authUtil.login(accountId, password, accountType);
    }

    @Override
    public String changePassword(String accountId, String oldPassword, String newPassword, int accountType) {
        return authUtil.changePassword(accountId, oldPassword, newPassword, accountType);
    }

    @Override
    public String auditQualification(String accountId) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        Account account = accountMapper.selectOne(queryWrapper);
        
        if (account == null) {
            return "用户不存在";
        }

        account.setStatus(1);
        account.setUpdatedAt(LocalDateTime.now());
        accountMapper.updateById(account);
        try {
            //将审核的数据进行上链（账号，是否提交合格的资质（1），角色种类）
            List <Object> funcParam = new ArrayList<>();
            funcParam.add(accountId);
            funcParam.add(true);
            funcParam.add(account.getAccountType());
            weBASEUtils.funcPost( "AccountModule", "registerAccount", funcParam);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        finally {
            return "审核成功";
        }
    }

    @Override
    public List<Account> getAllUsers() {
        // 创建查询条件，排除 account_type = 5 的用户（管理员自己）
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("account_type", 5);
        queryWrapper.orderByDesc("created_at");

        List<Account> users = accountMapper.selectList(queryWrapper);
        
        // 直接返回用户列表
        return users;
    }
}